<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ page import="com.lp.cfg.ProConfig"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<!DOCTYPE html>
<html>
<head>
	<title><%=ProConfig.PROJECT_NAME %></title>
	<%@ include file="/WEB-INF/wechat/iot/common/resource_lib.jsp"%>
	<script type="text/javascript" src="<%=basePath%>/lib/mqtt/mqtt.min.js"></script>
	<script type="text/javascript" src="../../lib/layer/layer.js"></script>
	<style type="text/css">
		.sensor-container{
			background: transparent;width:100%;
		}
		.sensor-container img{
			vertical-align: middle;margin: 0 0 0 10px;width: 35px;
		}
		.layui-layer-input{
		    border: 1px solid #d9d9d9 !important;
		    outline: none !important;
		   
		}
		.edit-param{
			float: right;margin-right: 10px;width: 24px !important;
			padding: 5px 10px;
		}
		.sensor-container .sensor-name{
			margin-left: 15px;font-size: 14px; 
		}
		.sensor-container .sensor-value{
			float: right;font-size: 24px;margin-right: 10px; color: #008fcd;
		}
		
		.sensor-container .sensor-type{
			float: right;font-size: 20px;margin-right: 13px;
		}
		.sensor-container img.sensor-control{
			float: right;  padding-right: 13px;;
		}
		.weui-media-box{
			padding: 7px;
		}
		
		.tempdata{
			font-size: 12px;
		    color: #666;
		    text-align: center;
		    padding: 10px;
		}
		.weui-panel.weui-panel_access.active .weui-panel__bd {
			display: none;
		}
		.weui-panel.weui-panel_access.active .weui-panel__hd{
			background: #f1f1f1;
		}

	</style>
</head>
<body>
	<div class="t-c title-info" >
		<span>Device information</span>
		<div class="back" onclick="forward('/wiot/scene')" style=" position: fixed;top: 0px;" >Back</div>
		<!--<div class="videoback"  onclick="forwardVideo()" style=" position: fixed;top: 0px;right:10px;" >
		</span>Surveillance</div>-->
	</div>
	<div style="height: 50px;"></div>
	<div class="container">
	
	</div>
	<div class="hide" id="hideContainer" >
	</div>
	<%@ include file="/WEB-INF/wechat/iot/common/pager.jsp"%>
	<div id="template0" class="hide">
		<div class="weui-panel weui-panel_access noid-{5}" >
			<div class="weui-panel__hd pointer">
				<span>{0}</span>
				<span class="{4}">{1}</span>
				<span class="float-right" style="color:#3499da; 
								border: 1px solid #3499da; border-radius: 3px;padding: 1px 2px; " onclick="forwrdSetting({5})" >Setting</span>
			</div>
			<div class="weui-panel__bd">
				{3}
			</div>
		</div>
	</div>
	
	<!-- 连续型 -->
	<div id="template1" class="hide">
		<a href="javascript:void(0);" class="weui-media-box weui-media-box_appmsg">
			<div class="clear sensor-container switchbtn" url="/wiot/sensor?id={2}&did={3}" tag="<%=basePath%>/service/iot/sensors_detail?id={2}&sid={3}">
		    	<img src="<%=basePath%>/image/oss/iot/{4}.png" />
		    	<span class="sensor-name" >{0}</span>
		    	<img class="edit-param {5}" onclick="downparam({2})"  src="<%=basePath%>/image/wechat/iot/edit.png" >
		    	<span class="sensor-value" >{1}</span>
		    </div>
		</a> 
	</div>
	<!-- 开关 -->
	<div id="template2" class="hide">
		<a href="javascript:void(0);" class="weui-media-box weui-media-box_appmsg">
			<div class="clear sensor-container switchbtn" url="/wiot/sensor?id={2}&did={4}" tag="<%=basePath%>/service/iot/sensors_detail?id={2}&sid={4}">
		    	<img src="<%=basePath%>/image/oss/iot/{6}.png" /> 
		    	<span class="sensor-name" >{0}</span>
		    	<img class="edit-param {7}" onclick="downparam({2})" src="<%=basePath%>/image/wechat/iot/edit.png" >
		    	<img style="width: 65px;margin-top: 3px;" tag="{5}" onclick="switchSensor(this,{2},{3})" {1} class="sensor-control" /> 
		    </div>
		</a>
	</div>
	<!-- 点动 -->
	<div id="template6" class="hide">
		<a href="javascript:void(0);" class="weui-media-box weui-media-box_appmsg">
			<div class="clear sensor-container switchbtn" url="/wiot/sensor?id={2}&did={4}" tag="<%=basePath%>/service/iot/sensors_detail?id={2}&sid={4}">
		    	<img src="<%=basePath%>/image/oss/iot/{6}.png" /> 
		    	<span class="sensor-name">{0}</span>
		    	<img style="width: 30px;margin-top: 3px;margin-right: 8px;" tag="{5}" onclick="switchSensordian(this,{2},{3})" {1} class="sensor-control" /> 
		    </div>
		</a>
	</div>
	<!-- 离散 -->
	<div id="template3" class="hide">
		<a href="javascript:void(0);" class="weui-media-box weui-media-box_appmsg">
			<div class="clear sensor-container switchbtn" url="/wiot/sensor?id={2}&did={3}" tag="<%=basePath%>/service/iot/sensors_detail?id={2}&sid={3}">
		    	<img src="<%=basePath%>/image/oss/iot/{4}.png" />
		    	<span class="sensor-name" >{0}</span>
		    	<img class="edit-param {5}" onclick="downparam({2})" src="<%=basePath%>/image/wechat/iot/edit.png" >
		    	<span class="sensor-value" >{1}</span>
		    </div>
		</a>
	</div>
	<!--定位型 -->
	<div id="template4" class="hide">
		<a href="javascript:void(0);" class="weui-media-box weui-media-box_appmsg">
			<div class="clear sensor-container" tag="<%=basePath%>/service/iot/sensors_detail?id={2}&sid={3}">
		    	<img src="<%=basePath%>/image/oss/iot/{4}.png" />
		    	<span class="sensor-name" >{0}</span>
		    	<span style="font-size: 17px;margin-top: 3px;" class="sensor-value" >{1}</span>
		    </div>
		</a>
	</div>

</body>
<script type="text/javascript">
	
	function forwrdSetting(deviceId){
		forward('/wiot/device_setting?id='+deviceId+'&sid='+ GetQueryString("id") );
	}
	
	/**
	 * 数据下发
	 */
	function downparam(id){
		layer.prompt({title: 'Data delivery', formType: 3}, function(val, index){
			commonAjax('PUT',localUrl+'/sensor/param/down.json', {sdata : val  ,id:id  },function(data){
				if(isOK(data)){
					tip("Write command successfully, please wait...");  
				}else{
					$.toptip(data.statusMsg, 'error');
				}	
			});			
			layer.close(index);
		});
		return false;
	}
	
	function getDisInfo(data){
		var t =eval('('+ gdv( data.infos,'{}') +')');
		if( t!= null && t.readType == 1){
			return "" ;
		}else{
			return "hide" ;
		}
	}
	
	//客户端
	var client ;
	function mqttInit(){
		// 连接选项
		const options = {
		      connectTimeout: 4000, // 超时时间
		      // 认证信息
		      clientId: 'brower_' + parseInt(Math.random()/31.1*10000000000),
		      username: '<%=ProConfig.MQTT.USERNAME%>',
		      password: '<%=ProConfig.MQTT.PASSWORD%>',
		}
		client = mqtt.connect('ws://'+document.domain+':8083/mqtt', options) ;
		client.on('reconnect', function(error)  {
			for(var i=1;i< paged;i++){
				reflesh(i);
			}
		})
		client.on('error', function(error) {
		    console.log('连接失败:', error)
		})
		client.on('message', function(topic, message,s) {
			if( message.toString() == '1' ){
				for(var i=1;i< paged;i++){
					reflesh(i);
				}
			}
		})
	}
	
	
	// 查询条件
	// 获取scene id
	var scene_id = GetQueryString("id") ;
	
	var data =  {scene_id: scene_id , node_data_type:0 } ;
	var paged = 1;
	
	$(function(){
		
		mqttInit();
		
		setTimeout( function() {
			var tempT = "/scene/update/"+ scene_id ;
			client.subscribe(tempT );
			client.publish('/sys/update/scene' , scene_id );
		}, 1000);
		
		getData(paged++);
		var loading = false;  //状态标记
		$(document.body).infinite().on("infinite", function() {
			if (loading)
				return;
			loading = true;
			setTimeout(function() {
				// 获取商品信息
				getData(paged++);
			}, 500); 
		});
		
		function getData(paged){
			var sid = GetQueryString("id") ;
			postAjax(localUrl+"/page/node/sensor/lists.json?pageSize=6&paged="+paged , data ,function(data){
				if(isOK(data)){
					var dataObj = data.data.data ;
					for(var i=0; i <dataObj.length;i++){
						$(".container").append($("#template0").html().format(dataObj[i].name ,dataObj[i].data.iot_node_status
											,disvalue(dataObj[i].device_code,10) 
											,getSensorListHtml(dataObj[i].iotSensorList,sid ,dataObj[i].iot_node_status ) 
											, getDeviceState(dataObj[i].iot_node_status),
											 dataObj[i].id ) );
					}
					
					if(data.data.totalPage > data.data.paged){
						loading = false;						
					}else{
						loading =true ;	
					}
				}else{
					loading =true ;	
				}
				// 传data就可以，分页的
				pagerinit(data,".container");
			});
		}
		
		setInterval(function() {
			for(var i=1;i< paged;i++){
				reflesh(i);
			}
		}, 60 * 1000);
		
		// 点击激活
		$(document).delegate(".weui-panel.weui-panel_access .weui-panel__hd","click",function(){
			if( $(this).parent().hasClass("active")){
				$(this).parent().removeClass("active");
			}else{
				$(this).parent().addClass("active");
			}
		})
		
		// 委托冒泡
		$(document).on("click",".sensor-control",function(e){
			e.stopPropagation();
		})
		
		$(document).on("click",".edit-param",function(e){
			e.stopPropagation();
		})
		
		/**
		* 跳转
		*/
		$(document).on("click",".switchbtn",function(){
			forward( $(this).attr("url") );
		})
		
	})
	
	// 更新数值
	function reflesh(paged){
		var sid = GetQueryString("id") ;
		postAjax(localUrl+"/page/node/sensor/lists.json?pageSize=6&paged="+paged , data ,function(data){
			if(isOK(data)){
				var dataObj = data.data.data ;
				for(var i=0; i <dataObj.length;i++){
					$("#hideContainer").append( $("#template0").html().format(dataObj[i].name ,dataObj[i].data.iot_node_status
										,disvalue(dataObj[i].device_code,10) 
										,getSensorListHtml(dataObj[i].iotSensorList,sid , dataObj[i].iot_node_status) 
										, getDeviceState(dataObj[i].iot_node_status)
										, dataObj[i].id) );
					$(".container .noid-"+dataObj[i].id  ).html( $("#hideContainer .noid-"+dataObj[i].id).html() );
					$("#hideContainer").empty();
				}
			}
		});
	}
	
	function switchSensordian(obj,id,value){
		commonAjax('PUT',localUrl+"/sensor/control/realtime/update", {id:id,request_sdata: value  },function(data){
			if(isOK(data)){
				tip("Delivered successfully");
			}else{
				tip(data.statusMsg);
			}
		});
	}
	
	/**
	 * 控制
	 */
	 function switchSensor(obj,id,value){
		var obj = $(obj) ;
		var requestData = '',src='' ;
		if( obj.attr("src").indexOf("loading") >-1  ){
			return ;
		}
		var measure_type_value = obj.attr("tag");
		if(convertControl(value,measure_type_value,'打开')){
			requestData = convertControl(value,measure_type_value,'打开');
			src = "<%=basePath%>/image/oss/iot/off_loading.gif";
		}else if(convertControl(value,measure_type_value,'关闭')){
			requestData =convertControl(value,measure_type_value,'关闭') ;
			src = "<%=basePath%>/image/oss/iot/on_loading.gif" ;
		}else if(convertControl(value,measure_type_value,'开门成功')){
			requestData = convertControl(value,measure_type_value,'开门成功');
			src = "<%=basePath%>/image/oss/iot/off_loading.gif";
		}else if(convertControl(value,measure_type_value,'正常')){
			requestData = convertControl(value,measure_type_value,'正常');
			src = "<%=basePath%>/image/oss/iot/on_loading.gif";
		}
		obj.attr("src",src);
		commonAjax('PUT',localUrl+"/sensor/control/realtime/update", {id:id,request_sdata:requestData  },function(data){
			if(isOK(data)){
				obj.attr("src",src);
			}else{
				$.toptip(data.statusMsg, 'error');
			}
		});
		return false;
	}
	
	function getDeviceState(state){
		if(state == 16 ){
			return "state";
		}else if(state == 19 || state == 17){
			return "state-red" ;
		}else if(state == 18 ){
			return "state-default" ;
		}
	}
	
	function getSensorListHtml(dataT,sid , node_status ){
		var str = '' ;
		var src1 = 'src="<%=basePath%>/image/oss/iot/on.png"';
		var src2 = 'src="<%=basePath%>/image/oss/iot/off.png"';
		for(var i=0;i<dataT.length;i++){
			if( dataT[i].data_type ==2){
				continue ;
			}
			// 传感器logo数据
			var sensorLogo = dataT[i].measure_unit_type ;
			if( dataT[i].iot_sensor_type == 25 ){
				
				str+=$("#template1").html().format(disvalue(dataT[i].name,15),
						getDsv( gdv(dataT[i].sdata,0),node_status ) +" "+dataT[i].data.measure_unit_type,dataT[i].id,sid,sensorLogo , getDisInfo(dataT[i]) );
			}else if( dataT[i].iot_sensor_type == 26 ){
				
				if( dataT[i].measure_unit_type == 250 ){
					str+=$("#template3").html().format(disvalue(dataT[i].name,15),
							getDsv( getWindUint(gdv(dataT[i].sdata,0)) ,node_status) ,dataT[i].id,sid,sensorLogo, getDisInfo(dataT[i]));
				}else{
					str+=$("#template3").html().format(disvalue(dataT[i].name,15),
							getDsv( gdv(dataT[i].data.measure_unit_type,'-') , node_status) ,dataT[i].id,sid,sensorLogo, getDisInfo(dataT[i]));
				}
				
			}else if( dataT[i].iot_sensor_type == 27  ){
				str+=$("#template2").html().format(disvalue(dataT[i].name,15),
						tom( getSwitch( dataT[i].sdata, node_status)  == 1.0 ,src1,src2 ),
						dataT[i].id,dataT[i].sdata,sid,dataT[i].data.measure_unit_type_value,sensorLogo, getDisInfo(dataT[i]) );
			}else if(dataT[i].iot_sensor_type == 90 ){
				
				str+=$("#template4").html().format(disvalue(dataT[i].name,15),
						getDsv( gdv(dataT[i].str_sdata,'-'),node_status)  ,dataT[i].id,sid,sensorLogo);
			}else if(dataT[i].iot_sensor_type == 190){
				
				str+=$("#template6").html().format(disvalue(dataT[i].name,15),
						'src="<%=basePath%>/image/oss/iot/switch.png"',
						dataT[i].id,dataT[i].param_type,sid,dataT[i].data.measure_unit_type_value,sensorLogo );
				
				
			}
		}
		if(validater.empty(str)){
			str = "<p class='tempdata'>No data available</p>";
		}
		return str ;
	}
	
	function getSwitch(value, status){
		if( status != 16 ){
			return 0 ;
		}else{
			return value ;
		}
	}

	function getDsv(value ,status ){
		if( status != 16 ){
			return "-" ;
		}else{
			return value ;
		}
	}
	
	function forwardVideo(){
		forward('/wiot/video?id='+GetQueryString("id") );
	}
	
	function getWindUint(sdata){
		if( sdata == 0 ){
			return "北风 " ;
		}else if( sdata >0 && sdata <90 ){
			return "东北 ";
		}else if( sdata == 90 ){
			return "东 ";
		}else if( sdata >90 && sdata <180 ){
			return "东南 ";
		}else if( sdata== 180 ){
			return "南 ";
		}else if( sdata >180 && sdata <270 ){
			return "西南 ";
		}else if( sdata ==270 ){
			return "西 ";
		}else if( sdata >270 ){
			return "西北 ";
		}
	}
</script>
</html>